package com.guyaogg.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guyaogg.common.constant.WareConstant;
import com.guyaogg.common.exception.MergePurchaseException;
import com.guyaogg.common.utils.PageUtils;
import com.guyaogg.common.utils.Query;
import com.guyaogg.gulimall.ware.dao.PurchaseDao;
import com.guyaogg.gulimall.ware.entity.PurchaseDetailEntity;
import com.guyaogg.gulimall.ware.entity.PurchaseEntity;
import com.guyaogg.gulimall.ware.service.PurchaseDetailService;
import com.guyaogg.gulimall.ware.service.PurchaseService;
import com.guyaogg.gulimall.ware.service.WareSkuService;
import com.guyaogg.gulimall.ware.vo.MergeVO;
import com.guyaogg.gulimall.ware.vo.PurchaseDoneVO;
import com.guyaogg.gulimall.ware.vo.PurchaseItemDoneVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @SuppressWarnings("AlibabaTransactionMustHaveRollback")
    @Transactional
    @Override
    public void mergePurchase(MergeVO mergeVO) {
        // TODO 确认采购单状态 0/1 才合并

        // 查询采购单状态
        mergeVO.getItems().forEach(item -> {
            Integer status = purchaseDetailService.getOne(new QueryWrapper<PurchaseDetailEntity>().eq("id", item)).getStatus();
            if (!(status == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode() ||
                    status == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode())) {
                throw new MergePurchaseException("状态不合法");
            }
        });
        Long purchaseId = mergeVO.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        List<Long> items = mergeVO.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

    /**
     * @param ids 采购单 id
     */
    @SuppressWarnings("AlibabaTransactionMustHaveRollback")
    @Transactional
    @Override
    public void received(List<Long> ids) {
        // 1.确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item -> item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()
        ).peek(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
        }).collect(Collectors.toList());
        // 2.改变采购单的状态
        this.updateBatchById(purchaseEntities);

        // 3.改变采购项的状态
        purchaseEntities.forEach(item -> {
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().peek(entity -> {
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);

        });
    }

    @Override
    public void done(PurchaseDoneVO purchaseDoneVO) {
        // TODO 先检查状态，提交过了就不能提交了已完成或有异常
        Long doneVOId = purchaseDoneVO.getId();
        // 改变采购项状态
        boolean flag = true;
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVO item : purchaseDoneVO.getItems()) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HAS_ERROR.getCode()) {
                flag = false;
                purchaseDetailEntity.setStatus(item.getStatus());

            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 将成功采购的进行入库
                PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());

                wareSkuService.addStock(byId.getSkuId(),byId.getWareId(),byId.getSkuNum());

            }
            purchaseDetailEntity.setId(item.getItemId());
            updates.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(updates);
        // 改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVOId);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);


    }

}